package com.manager.core.shiro.config;

import com.manager.commons.Constant;
import com.manager.commons.base.SessionUser;
import com.manager.core.shiro.core.entity.UserView;
import com.manager.core.shiro.core.service.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Shiro工具类
 */
@Component
public class ShiroUtil {
	@Autowired
	ShiroService shiroService;

	public static ShiroUtil shiroUtil;

	@PostConstruct
	public void init() {
		shiroUtil = this;
		shiroUtil.shiroService = this.shiroService;
	}

	/**
	 * 获取当前登录帐号
	 *
	 * @return 用户帐号
	 */
	public static String currentAccount() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser != null)
			return currentUser.getPrincipal() == null ? null : currentUser.getPrincipal().toString();
		else
			return null;
	}

	/**
	 * 设置当前登录角色
	 *
	 */
	public static void setCurrentRole() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser != null) {
			String account = currentUser.getPrincipal() == null ? null : currentUser.getPrincipal().toString();
			Session session = currentUser.getSession();
			UserView userView = shiroUtil.shiroService.queryUserView(account);
			SessionUser sessionUser = new SessionUser(userView, userView.getPu_id(), userView.getPu_name(), account);
			session.setAttribute(Constant.LOGIN_USER_SESSION, sessionUser);
		}
	}

	/**
	 * 判断当前用户是否已登录
	 *
	 * @return
	 */
	public static boolean isAuthenticated() {
		Subject currentUser = SecurityUtils.getSubject();
		return currentUser.isAuthenticated();
	}
}